//
//  XYComposeViewController.swift
//  01-新浪微博
//
//  Created by 陈许亚 on 16/3/16.
//  Copyright © 2016年 cxy. All rights reserved.
//

/*1.实现textView的拖拽及设置方向属性，隐藏键盘
2.toolBar中按钮的实现
3.根据系统隐藏和显示键盘通知，得到offSet ,打印信息，更新toolBar的frame，加入动画使toolBar和键盘和谐，先收集约束，在数据刷新
//后刷新视图
self.view.layoutIfNeeded()

*/

import UIKit
import SnapKit
import AFNetworking
import SVProgressHUD

class XYComposeViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setUpUI()
        registNotification()
        
    }
    
    //设置子视图
    private func setUpUI(){
        //设置背景色，为了看上去界面不卡顿，不至于看到后面视图的颜色
        view.backgroundColor = UIColor.whiteColor()
        navBarItem()
        setTextView()
        setToolBar()
        //TODO:有什么用处   将移动toolBar子视图到上层
        view.bringSubviewToFront(toolBar)
        
    }
    
    //选择图片
    @objc private func choosePicture(){
        print("选择图片")
       
        UIView.animateWithDuration(0.25) { () -> Void in
            //设置选择图片的控制器的frame
            self.choosePictureVC.view.snp_makeConstraints(closure: { (make) -> Void in
                //先收集约束
                make.height.equalTo(screenHeight / 3 * 2)
            })
            //在进行更新
            self.view.layoutIfNeeded()
        }
        
    }
    //选择表情
    @objc private func chooseEmotions(){
        print("选择表情")
        UIView.animateWithDuration(0.25) { () -> Void in
            //设置选择表情的控制器的frame
        }
        self.view.layoutIfNeeded()

    }
    

    //关闭，销毁当前控制器
   @objc private func close(){
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    //发布微博
   @objc private func send(){
        //打印被调用的当前函数名
        print(__FUNCTION__)
        //发布微博，上传文字微博和图片微博
        //TODO:先封装HTTPClient,避免使用框架淘汰或者不更新的危险，猿题库唐巧
        //也可直接用AFN来实现
        let urlString = "https://api.weibo.com/2/statuses/update.json"
        guard let token = XYUserAccount.sharedAccount.access_token else {
            print("用户未登录，或登录过期")
            return
        }
        let parameters = ["access_token":token,"status":textView.text]
        let AFN = AFHTTPSessionManager()
        
        AFN.POST(urlString, parameters: parameters, success: { (_, result) -> Void in
            print(result)
            SVProgressHUD.showSuccessWithStatus("发布微博成功")
            self.close()
            
            }) { (_, error) -> Void in
                print(error)
                SVProgressHUD.showErrorWithStatus("发布微博失败")

        }
    }
    
    //注册通知
    private func registNotification(){
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyBoardChanged:", name: UIKeyboardWillChangeFrameNotification, object: nil)

    }
    func keyBoardChanged(note: NSNotification) {
        print(note)
        //获取动画时间
        let duration = (note.userInfo![UIKeyboardAnimationDurationUserInfoKey]  as! NSNumber).doubleValue
        let rect = (note.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        
        let offSet = -screenHeight + rect.origin.y
        
        UIView.animateWithDuration(duration) { () -> Void in
            //先收集约束
            self.toolBar.snp_updateConstraints(closure: { (make) -> Void in
                make.bottom.equalTo(offSet)
            })
            //再进行数据刷新，需要刷新的时候再刷新
            self.view.layoutIfNeeded()
        }
        
    }
    
    //销毁
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    
    //文本输入
    lazy var textView: UITextView = {
        let tv = UITextView()
//        tv.backgroundColor = UIColor.greenColor()
//        tv.text = "分享新鲜事..."
        tv.font = UIFont.systemFontOfSize(18)
        tv.textColor = UIColor.lightGrayColor()
        return tv
    }()
    
    //占位文本
    lazy var textLabel: UILabel = UIFactory.labelFactory("分享新鲜事...", textColor:  UIColor.redColor(), fontSize: 18)
    
    //toolBar
    lazy var toolBar: UIToolbar = UIToolbar()
    //图片选择器
    lazy var choosePictureVC: XYChoosePictureViewController = XYChoosePictureViewController()
    
}


//监听文本编辑的代理方法
//textView是UItextView，有delegate属性，代理遵守UItextViewDelegate协议
extension XYComposeViewController: UITextViewDelegate {
    func textViewDidChange(textView: UITextView) {
        print(textView.text)
        textLabel.hidden = textView.hasText()
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
}

extension XYComposeViewController {
    
    //设置toolBar
    private func setToolBar(){
        view.addSubview(toolBar)
        
        toolBar.snp_makeConstraints { (make) -> Void in
            make.left.right.bottom.equalTo(view)
        }
        toolBar.backgroundColor = UIColor.yellowColor()
        /**
        //1.将要用的图片以字典的形式放到数组中
        2.遍历数组，给toolBar中的按钮赋值，将遍历出来的
        */
        //实例化一个存放UIBarButtonItem类型的数组
        var items = [UIBarButtonItem]()
        let itemSet = [["imageName": "compose_toolbar_picture","actionName": "choosePicture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background","actionName": "chooseEmotions"],
            ["imageName": "compose_add_background"]]
        //遍历
        for item in itemSet {
            let imageName = item["imageName"]
            let btn = UIFactory.buttonWithImage(imageName!, backImageName:nil)
            //判断,Selector直接可以用一个“”字符串，系统会自动包装，如果是一个string类型的变量时要使用Selector()包装一下
            if let actionName = item["actionName"] {
                btn.addTarget(self, action: Selector(actionName), forControlEvents: .TouchUpInside)
            }
            //自定义样式的UIBarButtonItem
            let itemBar = UIBarButtonItem(customView: btn)
            //将自定义的UIBarButtonItem添加到数组中
            items.append(itemBar)
            
            //添加弹簧类型的item  FlexibleSpace: 可伸缩的弹簧
            let space = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
            items.append(space)
        }
        
        toolBar.items = items
        //删除最后一个
        toolBar.items?.removeLast()

    }
    
    
    //设置文本信息
    private func setTextView(){
        
        view.addSubview(textView)
        textView.snp_makeConstraints { (make) -> Void in
            make.left.right.equalTo(view)
            make.height.equalTo(screenHeight / 3)
            
        }
        //实现textView拖拽隐藏键盘
        //设置键盘的隐藏模式（ios7.0出现）
        textView.keyboardDismissMode = .OnDrag
        //可以垂直拖拽
        textView.alwaysBounceVertical = true
        
        //设置代理
        textView.delegate = self
        
        textView.addSubview(textLabel)
        
        textLabel.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(textView.snp_left).offset(5)
            make.top.equalTo(textView.snp_top).offset(8)
        }
        
    }
    
    //设置navigationItem
    private func navBarItem(){
        //navigationItem是一个容器
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", style: .Plain, target: self, action: "send")
        //开始是不能与用户交互的
        navigationItem.rightBarButtonItem?.enabled = false
        
        
        //设置titleView
        let myView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 40))
        //  myView.backgroundColor = UIColor.redColor()
        navigationItem.titleView = myView
        
        let titleLabel = UIFactory.labelFactory("发布微博", textColor: UIColor(white: 0.1, alpha: 1), fontSize: 17, alignment: .Center)
        myView.addSubview(titleLabel)
        
        let nameLabel = UIFactory.labelFactory(XYUserAccount.sharedAccount.name ?? "", textColor: UIColor.lightGrayColor(), fontSize: 15, alignment: .Center)
        myView.addSubview(nameLabel)
        
        titleLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(myView.snp_top)
            make.centerX.equalTo(myView.snp_centerX)
            
        }
        nameLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(titleLabel.snp_bottom)
            make.centerX.equalTo(myView.snp_centerX)
            
        }
    }

}